package cn.suchan.jianzhi.q12_power;

/**
 * 知识点：数值的整数次方
 * 题目描述
 * 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
 *
 * @author suchan
 * @date 2019/05/26
 */
public class Solution {

    public double Power(double base, int exponent) {

        /* 如果base = 0 输出0 */
        if (base >= -0.000001 && base <= 0.000001) {
            return 0;
        }

        if (exponent == 0) {
            return 1;
        }
        int abs = Math.abs(exponent);
        double result = positive(base, abs);
        if (exponent < 0) {
            return 1 / result;
        }
        return result;
    }

    /**
     * 正整数
     *
     * @param base
     * @param exponent
     */
    public double positive(double base, int exponent) {
        if (exponent == 1) {
            return base;
        }
        double result = base;
        for (int i = 2; i <= exponent; i++) {
            result = result * base;
        }
        return result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        double power = solution.Power(2, 3);
        System.out.println(power);
    }
}
